<template>
  <div class="register-wrapper">
    <!-- 头像logo -->
    <div class="register-logo">
      <van-image :src="imgUrl"></van-image>
    </div>
    <!-- 表单 -->
    <div class="register-form">
      <van-config-provider :theme-vars="themeVars">
        <van-form @submit="handleregister" ref="registerFormRef" validate-trigger="onSubmit">
          <van-cell-group inset>
            <van-field
              ref="usernameRef"
              v-model="registerForm.username"
              name="validateMobile"
              maxlength="11"
              placeholder="请输入手机号"
              :rules="registerRules.username"
            />
            <van-field
              ref="passwordRef"
              v-model="registerForm.password"
              type="text"
              name="validatePassword"
              placeholder="请输入密码"
              :rules="registerRules.password"
            />
            <van-field
              ref="passwordsedRef"
              v-model="registerForm.passwordsed"
              type="text"
              name="validatepasswordsed"
              placeholder="请再次输入密码"
              :rules="registerRules.passwordsed"
            />

            <van-field
              v-model="registerForm.smsCode"
              type="number"
              name="validateSmsCode"
              placeholder="请输入短信验证码"
							maxlength="6"
              ref="smsCodeRef"
              :rules="registerRules.smsCode"
            >
              <template #button>
                <van-button size="small" type="primary" @click="sendCode" :loading="codebtn">{{ smsText }}</van-button>
              </template>
            </van-field>
          </van-cell-group>
          <div class="btn-box">
            <van-button
              round
              block
              :loading="loading"
              loading-type="spinner"
              type="primary"
              native-type="submit"
            >
              注册
            </van-button>
          </div>
        </van-form>
      </van-config-provider>
      <!-- 立即注册 -->
      <div class="register-textlist">
        <span @click="goPage('register')">已有账号去登陆</span>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import { defineComponent, reactive, ref, toRefs, onMounted } from 'vue'
import { Form, Notify } from 'vant'
import { useRouter } from 'vue-router'
import { validateMobile, validatePassword, validateSmsCode } from '@utils/validate'
import { getImgUrl, Encrypt } from '@utils/index'
import { useStore } from 'vuex'
import { IGlobalState } from '@/store'
import useRouteQuery from './hooks/useRouteQuery'
import { uuid } from 'vue-uuid'
import * as Types from '@/store/action-types'

type IVantFromInstance = InstanceType<typeof Form>
export default defineComponent({
  name: 'Register',
  setup() {
    let store = useStore<IGlobalState>()
    const router = useRouter()
    const loading = ref(false) // 登录加载状态
    // form ref
    const registerFormRef = ref<IVantFromInstance | null>(null)
    // form username ref
    const usernameRef = ref<HTMLInputElement | null>(null)
    // form password ref
    const passwordRef = ref<HTMLInputElement | null>(null)
    const passwordsedRef = ref<HTMLInputElement | null>(null)
    const smsCodeRef = ref<HTMLInputElement | null>(null)
    // themeVars 内的值会被转换成对应 CSS 变量
    // 比如 sliderBarHeight 会转换成 `--van-slider-bar-height`
    const themeVars = {
      buttonPrimaryBorderColor: '#3CB677',
      buttonPrimaryBackgroundColor: '#3CB677',
    }
    // logo
    const imgUrl = getImgUrl('login-logo.png')
    // uuid
    let uuId = ref(uuid.v1())
    //
    const validatepasswordsed = (password: string) => {
      if (!password) return false
      return registerState.registerForm.password === password
    }
		//data
    const registerState = reactive({
      registerForm: {
        username: '13512345678', //13512345678
        password: '123wer!@', //123wer!@
        passwordsed: '123wer!@',
        smsCode: '',
        smsSqe: '',
        uuid: '',
      },
      registerRules: {
        username: [
          {
            required: true,
            trigger: 'onBlur',
            message: '请输入手机号码！',
          },
          { trigger: 'onBlur', validator: validateMobile, message: '请输入合法格式的手机号码' },
        ],
        password: [
          {
            required: true,
            trigger: 'onBlur',
            message: '请输入密码！',
          },
          {
            trigger: 'onBlur',
            validator: validatePassword,
            message: '密码必须由数字、字母、特殊字符组合',
          },
        ],
        passwordsed: [
          {
            required: true,
            trigger: 'onBlur',
            message: '请输入密码！',
          },
          {
            trigger: 'onBlur',
            validator: validatepasswordsed,
            message: '两次密码不一样',
          },
        ],
        smsCode: [
          {
            required: true,
            trigger: 'onBlur',
            message: '请输入验证码！',
          },
          {
            trigger: 'onBlur',
            validator: validateSmsCode,
            message: '验证码为6位数字',
          },
        ],
      },
      smsText: '发送验证码',
      timer: null,
      time_count: 60,
			codebtn:false
    })
		
    //发送验证码
    const sendCode = (_values: any) => {
      loading.value = true
      let params = {
        username: registerState.registerForm.username,
        uuid: uuId,
      }
      store
        .dispatch(`user/${Types.SET_SMSCODE}`, params)
        .then((_res: any) => {
          loading.value = false
          // 倒计时
          countdown()
        })
        .catch((_err: any) => {
          loading.value = false
          Notify({ type: 'danger', message: _err })
        })
    }
    //倒计时
		const countdown = () =>{
			if (!registerState.timer) {
            registerState.timer = setInterval(() => {
              if (registerState.time_count > 0) {
                registerState.time_count--
                registerState.smsText = '重新发送' + registerState.time_count + 's'
              } else {
                registerState.smsText = '发送验证码'
                clearInterval(registerState.timer)
                registerState.timer = null
                registerState.time_count = 60
                registerState.codebtn = false
              }
            }, 1000)
          }
		}
    // 重定向router query处理
    const { redirect, otherQuery } = useRouteQuery()

    // register
    const handleregister = (values: any) => {
			const smsSqe = store.state.user.registerForm.smsSqe
			if(!smsSqe){
				Notify({ type: 'danger', message: '请先发送验证码' })
				return false
			}
      loading.value = true
      //加密
      let { uuid,username, password, passwordsed,smsCode} = registerState.registerForm
      let encryptWord = Encrypt(
        password,
        uuid.slice(0, 16),
        uuid.slice(uuid.length - 16, uuid.length)
      )
			let encryptWord2 = Encrypt(
        passwordsed,
        uuid.slice(0, 16),
        uuid.slice(uuid.length - 16, uuid.length)
      )
			let param = { uuid, username, password: encryptWord,passwordsed:encryptWord2,smsCode,smsSqe }
      // 发送注册请求
      store
        .dispatch(`user/${Types.SET_REGISTER}`, param)
        .then(_res => {
          // 登录成功后跳转之前被访问页或首页
					Notify({ type: 'success', message: '注册成功' })
					setTimeout(()=>{
						router.push({
            path: redirect.value || '/login',
            query: otherQuery.value,
          })
					},2000)
          
        })
        .catch(_err => {
          loading.value = false
          Notify({ type: 'danger', message: _err })
        })
    }
    //页面跳转
    const goPage = (urlName: string) => {
      router.push({
        path: redirect.value || '/' + urlName,
        query: otherQuery.value,
      })
    }
    // 自动获取焦点
    onMounted(() => {
      if (registerState.registerForm.username === '') {
        ;(usernameRef.value as HTMLInputElement).focus()
      } else if (registerState.registerForm.password === '') {
        ;(passwordRef.value as HTMLInputElement).focus()
      } else if (registerState.registerForm.passwordsed === '') {
        ;(passwordRef.value as HTMLInputElement).focus()
      } else if (registerState.registerForm.smsCode === '') {
        ;(passwordRef.value as HTMLInputElement).focus()
      }
    })
    return {
      themeVars,
      imgUrl,
      loading,
      registerFormRef,
      usernameRef,
      passwordRef,
      passwordsedRef,
      smsCodeRef,
      handleregister,
      sendCode,
      goPage,
      ...toRefs(registerState),
    }
  },
})
</script>
<style lang="scss">
@import '@/styles/viriables.scss';
@import '@/styles/mixins.scss';
.register-wrapper {
  width: 100%;
  box-sizing: border-box;
  margin-top: 100px;
  @include flexCenter();
  .register-logo {
    @include circle(39px);
    padding: 5%;
    background-color: $main-color;
    margin-bottom: 40px;
  }
  .register-form {
    width: 80%;
  }
  .btn-box {
    margin: 22px;
  }
  .register-textlist {
    margin: 15px 0;
    color: $secondary-font-color;
    text-align: center;
    span {
      font-size: $fnSize12;
      margin: 0 10px;
    }
  }
}
</style>
